package com.example.authforcmcc;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public final class HttpUtils {

	private static final int MANAGER_TIMEOUT = 1 * 1000;
	private static final int REQUEST_TIMEOUT = 4 * 1000;
	private static final int SO_TIMEOUT = 4 * 1000;
	private static final String CHARSET = HTTP.UTF_8;
	

	private static final String TAG = "HttpRequest";

	public static HttpClient getHttpClient() {
		HttpParams params = new BasicHttpParams();

		// 设置�?些基本参�?
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, CHARSET);
		HttpProtocolParams.setUseExpectContinue(params, true);
		HttpProtocolParams
				.setUserAgent(
						params,
						"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
								+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");

		// 从连接池中取连接的超时时�?
		ConnManagerParams.setTimeout(params, MANAGER_TIMEOUT);
		// 连接超时
		HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
		// 请求超时
		HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);

		// 设置我们的HttpClient支持HTTP和HTTPS两种模式
		SchemeRegistry schReg = new SchemeRegistry();
		SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
		sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		schReg.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schReg.register(new Scheme("https", sf, 443));

		// 使用线程安全的连接管理来创建HttpClient
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
				params, schReg);
		return new DefaultHttpClient(conMgr, params);
	}

	public static HttpClient getSSLHttpClient() {

		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore
					.getDefaultType());
			trustStore.load(null, null);
			SSLSocketFactory sf = new MySecureProtocolSocketFactory(trustStore);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			registry.register(new Scheme("https", sf, 443));
			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			//HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
			HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
			ClientConnectionManager ccm = new ThreadSafeClientConnManager(
					params, registry);

			return new DefaultHttpClient(ccm, params);

		} catch (Exception e) {
			Log.e(TAG, "创建HTTP Client出错�?", e);
			// e.printStackTrace();
			return new DefaultHttpClient();
		}

	}

	public static InputStream retriveInputSteam(String requrl) {
		InputStream is = null;
		URL url = null;
		// URLConnection urlconn = null;
		HttpURLConnection conn = null;
		try {
			url = new URL(requrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			int responseCode = conn.getResponseCode();
			if (responseCode == 200) {
				is = conn.getInputStream();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return is;
	}

	public static InputStream getInputStream(String url) throws Exception {
		HttpClient client = null;
		InputStream is = null;
		client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		HttpResponse response = client.execute(get);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			is = response.getEntity().getContent();
		}
		return is;
	}

	public static String Post(String url, List<NameValuePair> params) {
		String reply = null;
		HttpClient client = null;
		try {
			client = getHttpClient();
			HttpPost post = new HttpPost(url);
			post.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				reply = EntityUtils.toString(response.getEntity());
			}
		} catch (Exception e) {
			Log.e(TAG, "�?" + url + "发出POST请求出错�?", e);
		} finally {
			if (null != client) {
				client.getConnectionManager().shutdown();
			}
		}
		return reply;
	}

	public static long getContentLength(String url) {
		long len = 0;
		if (!url.startsWith("http://")) {
			url = "http://" + url;
		}
		HttpClient c = getHttpClient();
		HttpGet get = new HttpGet(url);
		try {
			HttpResponse response = c.execute(get);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				len = (entity.getContentLength());
				Log.d(TAG, "获取" + url + "网页大小�?" + len);
			}

		} catch (Exception e) {
			Log.e(TAG, "获取" + url + "网页大小出错�?", e);
		} finally {
			c.getConnectionManager().shutdown();
		}
		return len;
	}

}
